<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Oauth2+Jwt实现基础的SSO | XY Blog</title><meta name="keywords" content="SSO"><meta name="author" content="XY"><meta name="copyright" content="XY"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="基于Oauth2和Jwt实现基础的SSO（单点登录功能）">
<meta property="og:type" content="article">
<meta property="og:title" content="Oauth2+Jwt实现基础的SSO">
<meta property="og:url" content="http://example.com/2023/04/07/Oauth2+Jwt%E5%AE%9E%E7%8E%B0%E5%9F%BA%E7%A1%80%E7%9A%84SSO/index.html">
<meta property="og:site_name" content="XY Blog">
<meta property="og:description" content="基于Oauth2和Jwt实现基础的SSO（单点登录功能）">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/img/sso.jfif">
<meta property="article:published_time" content="2023-04-07T06:51:00.000Z">
<meta property="article:modified_time" content="2023-04-18T16:44:16.049Z">
<meta property="article:author" content="XY">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/img/sso.jfif"><link rel="shortcut icon" href="/img/liuxing.jpg"><link rel="canonical" href="http://example.com/2023/04/07/Oauth2+Jwt%E5%AE%9E%E7%8E%B0%E5%9F%BA%E7%A1%80%E7%9A%84SSO/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"简","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Oauth2+Jwt实现基础的SSO',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-04-19 00:44:16'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/liuxing.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">9</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">5</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">1</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标籤</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">XY Blog</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标籤</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">Oauth2+Jwt实现基础的SSO</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-04-07T06:51:00.000Z" title="发表于 2023-04-07 14:51:00">2023-04-07</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-04-18T16:44:16.049Z" title="更新于 2023-04-19 00:44:16">2023-04-19</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a></span></div><div class="meta-secondline"></div></div></div><article class="post-content" id="article-container"><p>项目地址<a target="_blank" rel="noopener" href="https://github.com/sc-xy/jwt-sso-demo">sc-xy/jwt-sso-demo: 基于Oauth2和Jwt实现基础的SSO（单点登录功能） (github.com)</a></p>
<h2 id="名词解释"><a href="#名词解释" class="headerlink" title="名词解释"></a>名词解释</h2><div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:left">Oauth2</th>
<th style="text-align:right">一种开放标准协议用于授权访问用户在一个应用程序上拥有的资源，使得用户可以将他们的私人数据安全地共享给其他应用程序，而无需提供其用户名和密码</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left"><strong>JWT</strong></td>
<td style="text-align:right"><strong>一种开放标准的JSON格式的令牌，用于在网络应用之间传递声明</strong></td>
</tr>
<tr>
<td style="text-align:left"><strong>SSO</strong></td>
<td style="text-align:right"><strong>单点登录(Single Sign On)，当用户在身份认证服务器上登录一次以后，即可获得访问单点登录系统中其他关联系统和应用软件的权限</strong></td>
</tr>
</tbody>
</table>
</div>
<p>不难看出，我们想要实现<code>sso</code>必然需要一个认证中心和多个认证客户端应用，我们也分别实现<code>sso-server</code>和<code>sso-client</code>来实现单点登录功能</p>
<blockquote>
<p>项目环境</p>
<p><code>SDK</code>:1.8</p>
<p><code>springboot</code>:2.3.4.RELEASE</p>
<p><code>maven</code>:Apache Maven 3.9.0</p>
</blockquote>
<h2 id="SSO-Server"><a href="#SSO-Server" class="headerlink" title="SSO-Server"></a>SSO-Server</h2><h3 id="pom-xml-关键依赖"><a href="#pom-xml-关键依赖" class="headerlink" title="pom.xml 关键依赖"></a><code>pom.xml</code> 关键依赖</h3><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.security.oauth<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-security-oauth2<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.5.0.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.security<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-security-jwt<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1.1.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.security.oauth.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-security-oauth2-autoconfigure<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.3.3.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-security<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="项目结构"><a href="#项目结构" class="headerlink" title="项目结构"></a>项目结构</h3><p><img src="http://img.sc-xy.top/20230418212844.png" alt="image-20230418212843150"></p>
<h3 id="application-yml配置文件"><a href="#application-yml配置文件" class="headerlink" title="application.yml配置文件"></a><code>application.yml</code>配置文件</h3><figure class="highlight yml"><table><tr><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">8080</span></span><br><span class="line">  <span class="attr">servlet:</span></span><br><span class="line"><span class="comment">#    推荐不为空，否则可能出现认证失败问题</span></span><br><span class="line">    <span class="attr">context-path:</span> <span class="string">/server</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 数据库配置信息</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">datasource:</span></span><br><span class="line">    <span class="attr">driver-class-name:</span> <span class="string">com.mysql.cj.jdbc.Driver</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://localhost:3306/database?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=UTC</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># mybatis配置信息</span></span><br><span class="line"><span class="attr">mybatis:</span></span><br><span class="line">  <span class="attr">type-aliases-package:</span> <span class="string">com.xy.ssoserver.entity</span></span><br><span class="line">  <span class="attr">mapper-locations:</span> <span class="string">classpath:com.xy.ssoserver.mapper/*.xml</span></span><br><span class="line">  <span class="attr">configuration:</span></span><br><span class="line">    <span class="attr">map-underscore-to-camel-case:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<h3 id="SsoUserDetailServiceImpl用户认证服务"><a href="#SsoUserDetailServiceImpl用户认证服务" class="headerlink" title="SsoUserDetailServiceImpl用户认证服务"></a><code>SsoUserDetailServiceImpl</code>用户认证服务</h3><blockquote>
<p><code>UserService</code>主要用来获取用户的基本信息，<code>PassWordEncoder</code>会在后面的配置中解释</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SsoUserDetailServiceImpl</span> <span class="keyword">implements</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserService userService;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> PasswordEncoder passwordEncoder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line"><span class="comment">//        判断用户是否存在并返回</span></span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userService.loadUserByUsername(username);</span><br><span class="line">        <span class="keyword">if</span> (user == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UsernameNotFoundException</span>(<span class="string">&quot;用户不存在&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">org</span>.springframework.security.core.userdetails.User(user.getUsername(),</span><br><span class="line">                passwordEncoder.encode(user.getPassword()),</span><br><span class="line">                user.getRoles());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="WebSecurityConfig安全认证配置"><a href="#WebSecurityConfig安全认证配置" class="headerlink" title="WebSecurityConfig安全认证配置"></a><code>WebSecurityConfig</code>安全认证配置</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableWebSecurity</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebSecurityConfig</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    <span class="meta">@Lazy</span></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> SsoUserDetailServiceImpl ssoUserDetailService;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> PasswordEncoder <span class="title function_">passwordEncoder</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> JwtTokenStore <span class="title function_">jwtTokenStore</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">JwtTokenStore</span>(jwtAccessTokenConverter());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> JwtAccessTokenConverter <span class="title function_">jwtAccessTokenConverter</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">JwtAccessTokenConverter</span> <span class="variable">converter</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">JwtAccessTokenConverter</span>();</span><br><span class="line">        <span class="comment">// 指定singinKey，songinkey是认证中心验证客户端token是否合法的密钥</span></span><br><span class="line">        converter.setSigningKey(<span class="string">&quot;xy&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> converter;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        auth.userDetailsService(ssoUserDetailService).passwordEncoder(passwordEncoder());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 除了登录请求外的请求都需要认证，禁用csrf和cors</span></span><br><span class="line">        http.authorizeRequests()</span><br><span class="line">                .anyRequest()</span><br><span class="line">                .authenticated()</span><br><span class="line">                .and()</span><br><span class="line">                .formLogin()</span><br><span class="line">                .permitAll()</span><br><span class="line">                .and().csrf().disable().cors();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="SsoAuthorizationServiceConfig认证客户端配置"><a href="#SsoAuthorizationServiceConfig认证客户端配置" class="headerlink" title="SsoAuthorizationServiceConfig认证客户端配置"></a><code>SsoAuthorizationServiceConfig</code>认证客户端配置</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableAuthorizationServer</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SsoAuthorizationServerConfig</span> <span class="keyword">extends</span> <span class="title class_">AuthorizationServerConfigurerAdapter</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> PasswordEncoder passwordEncoder;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> JwtTokenStore jwtTokenStore;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> JwtAccessTokenConverter jwtAccessTokenConverter;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(ClientDetailsServiceConfigurer client)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 采用内存存储客户端信息</span></span><br><span class="line">        client.inMemory()</span><br><span class="line">                <span class="comment">// 注册一个客户端</span></span><br><span class="line">                .withClient(<span class="string">&quot;client1&quot;</span>)</span><br><span class="line">                <span class="comment">// 客户端密码</span></span><br><span class="line">                .secret(passwordEncoder.encode(<span class="string">&quot;client1secret&quot;</span>))</span><br><span class="line">                <span class="comment">// 令牌有效期1小时</span></span><br><span class="line">                .accessTokenValiditySeconds(<span class="number">3600</span>)</span><br><span class="line">                <span class="comment">// 重定向到客户端登陆界面</span></span><br><span class="line">                .redirectUris(<span class="string">&quot;http://localhost:8081/client1/login&quot;</span>)</span><br><span class="line">                <span class="comment">// 授权多种认证方式</span></span><br><span class="line">                .authorizedGrantTypes(<span class="string">&quot;authorization_code&quot;</span>, <span class="string">&quot;refresh_token&quot;</span>, <span class="string">&quot;password&quot;</span>)</span><br><span class="line">                <span class="comment">// 指定作用域为 all</span></span><br><span class="line">                .scopes(<span class="string">&quot;all&quot;</span>)</span><br><span class="line">                <span class="comment">// 需要手动授权</span></span><br><span class="line">                .autoApprove(<span class="literal">false</span>)</span><br><span class="line">                .and()</span><br><span class="line">                .withClient(<span class="string">&quot;client2&quot;</span>)</span><br><span class="line">                .secret(passwordEncoder.encode(<span class="string">&quot;client2secret&quot;</span>))</span><br><span class="line">                .accessTokenValiditySeconds(<span class="number">3600</span>)</span><br><span class="line">                .redirectUris(<span class="string">&quot;http://localhost:8082/client2/login&quot;</span>)</span><br><span class="line">                .authorizedGrantTypes(<span class="string">&quot;authorization_code&quot;</span>, <span class="string">&quot;refresh_token&quot;</span>, <span class="string">&quot;password&quot;</span>)</span><br><span class="line">                .scopes(<span class="string">&quot;all&quot;</span>)</span><br><span class="line">                .autoApprove(<span class="literal">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthorizationServerEndpointsConfigurer endpoints)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 配置令牌存储方式和令牌转换器</span></span><br><span class="line">        endpoints.tokenStore(jwtTokenStore)</span><br><span class="line">                .accessTokenConverter(jwtAccessTokenConverter);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthorizationServerSecurityConfigurer security)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 只有经过身份验证的客户端才能访问令牌密钥</span></span><br><span class="line">        security.tokenKeyAccess(<span class="string">&quot;isAuthenticated()&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="SSO-Client"><a href="#SSO-Client" class="headerlink" title="SSO-Client"></a>SSO-Client</h2><h3 id="pom-xml关键依赖"><a href="#pom-xml关键依赖" class="headerlink" title="pom.xml关键依赖"></a><code>pom.xml</code>关键依赖</h3><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span><span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.security.oauth<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-security-oauth2<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.5.0.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.security<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-security-jwt<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1.1.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.security.oauth.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-security-oauth2-autoconfigure<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.3.3.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-security<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="application-yml配置文件-1"><a href="#application-yml配置文件-1" class="headerlink" title="application.yml配置文件"></a><code>application.yml</code>配置文件</h3><figure class="highlight yml"><table><tr><td class="code"><pre><span class="line"><span class="attr">security:</span></span><br><span class="line">  <span class="attr">oauth2:</span></span><br><span class="line"><span class="comment">#    客户端配置</span></span><br><span class="line">    <span class="attr">client:</span></span><br><span class="line"><span class="comment">#      客户端用户名密码</span></span><br><span class="line">      <span class="attr">client-id:</span> <span class="string">client1</span></span><br><span class="line">      <span class="attr">client-secret:</span> <span class="string">client1secret</span></span><br><span class="line"><span class="comment">#      用户认证url</span></span><br><span class="line">      <span class="attr">user-authorization-uri:</span> <span class="string">http://localhost:8080/server/oauth/authorize</span></span><br><span class="line"><span class="comment">#      token验证url</span></span><br><span class="line">      <span class="attr">access-token-uri:</span> <span class="string">http://localhost:8080/server/oauth/token</span></span><br><span class="line">    <span class="attr">resource:</span></span><br><span class="line">      <span class="attr">jwt:</span></span><br><span class="line"><span class="comment">#        jwt密钥url</span></span><br><span class="line">        <span class="attr">key-uri:</span> <span class="string">http://localhost:8080/server/oauth/token_key</span></span><br><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">8081</span></span><br><span class="line">  <span class="attr">servlet:</span></span><br><span class="line">    <span class="attr">context-path:</span> <span class="string">/client1</span></span><br></pre></td></tr></table></figure>
<h3 id="SessionUtil获取用户信息工具类"><a href="#SessionUtil获取用户信息工具类" class="headerlink" title="SessionUtil获取用户信息工具类"></a><code>SessionUtil</code>获取用户信息工具类</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SessionUtil</span> &#123;</span><br><span class="line">    <span class="comment">// 获取当前用户认证信息</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Authentication <span class="title function_">getAuthentication</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> SecurityContextHolder.getContext().getAuthentication();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 获取当前用户的权限信息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> List&lt;String&gt; <span class="title function_">getAuthorities</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">Authentication</span> <span class="variable">authentication</span> <span class="operator">=</span> getAuthentication();</span><br><span class="line">        <span class="keyword">if</span> (authentication != <span class="literal">null</span> &amp;&amp; authentication.isAuthenticated()) &#123;</span><br><span class="line">            Collection&lt;? <span class="keyword">extends</span> <span class="title class_">GrantedAuthority</span>&gt; authorities = authentication.getAuthorities();</span><br><span class="line">            <span class="keyword">return</span> authorities.stream()</span><br><span class="line">                    .map(GrantedAuthority::getAuthority)</span><br><span class="line">                    .collect(Collectors.toList());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 获取当前用户名</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getCurrentUserName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">Authentication</span> <span class="variable">authentication</span> <span class="operator">=</span> getAuthentication();</span><br><span class="line">        <span class="keyword">if</span> (authentication.isAuthenticated() &amp;&amp; !(authentication <span class="keyword">instanceof</span> AnonymousAuthenticationToken)) &#123;</span><br><span class="line">            <span class="type">Object</span> <span class="variable">principal</span> <span class="operator">=</span> authentication.getPrincipal();</span><br><span class="line">            <span class="keyword">if</span> (principal <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">                <span class="keyword">return</span> (String) principal;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (principal <span class="keyword">instanceof</span> UserDetails) &#123;</span><br><span class="line">                <span class="type">String</span> <span class="variable">currentuser</span> <span class="operator">=</span> ((UserDetails) principal).getUsername();</span><br><span class="line">                <span class="keyword">return</span> currentuser;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;not instanceof UserDetails&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="WebConfig安全配置"><a href="#WebConfig安全配置" class="headerlink" title="WebConfig安全配置"></a><code>WebConfig</code>安全配置</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 启用Oauth2Sso</span></span><br><span class="line"><span class="meta">@EnableOAuth2Sso</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebConfig</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 注销后回调认证中心的注销url,所有请求都需要认证,禁用csrf</span></span><br><span class="line">        http.logout()</span><br><span class="line">                .logoutSuccessUrl(<span class="string">&quot;http://localhost:8080/server/exit&quot;</span>)</span><br><span class="line">                .and().authorizeRequests().anyRequest().authenticated()</span><br><span class="line">                .and().csrf().disable();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同样，<code>sso-client2</code>和<code>sso-client3</code>等等客户端的程序也如此</p>
<h2 id="验证结果"><a href="#验证结果" class="headerlink" title="验证结果"></a>验证结果</h2><blockquote>
<p>先后启动<code>sso-server</code> <code>sso-client1</code> <code>sso-client2</code></p>
</blockquote>
<p>访问<code>http://localhost:8081/client1/home/index</code>会跳转到<code>http://8080/server/login</code></p>
<p><img src="http://img.sc-xy.top/20230418225608.png" alt="image-20230418225607040"></p>
<p>当我们登录后会让我们手动授权~在sso-sver中配置过~</p>
<p><img src="http://img.sc-xy.top/20230418225938.png" alt="image-20230418225937213"></p>
<p>授权后跳转到<code>http://localhost:8081/client1/home/index</code></p>
<p><img src="http://img.sc-xy.top/20230418230037.png" alt="image-20230418230035002"></p>
<p>点击<code>跳转到Client2</code>后会让我们再次手动授权~这里不做演示~</p>
<p>点击<code>logout</code>后，我们会重定向到<code>http://localhost:8080/server/login</code>并消除我们在对应客户端和认证中心的用户信息</p>
<p><img src="http://img.sc-xy.top/20230418230234.png" alt="image-20230418230231963"></p>
<p>至此，我们的<code>SSO</code>已经成功运行了，其他不重要代码及整个项目可在我的<code>github</code>仓库<a target="_blank" rel="noopener" href="https://github.com/sc-xy/jwt-sso-demo">jwt-sso-demo</a>中访问</p>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/java/">java</a></div><div class="post_share"><div class="social-share" data-image="/img/sso.jfif" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/2022/11/15/Java%E8%BF%9E%E6%8E%A5MySQL%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/"><img class="next-cover" src="/img/Java_MySQL.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java连接MySQL基础教程(JDBC)</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/11/07/Json+MySQL%E5%88%9D%E6%8E%A2/" title="Json文件读取（Java）"><img class="cover" src="/img/json.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-11-07</div><div class="title">Json文件读取（Java）</div></div></a></div><div><a href="/2022/11/15/Java%E8%BF%9E%E6%8E%A5MySQL%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/" title="Java连接MySQL基础教程(JDBC)"><img class="cover" src="/img/Java_MySQL.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-11-15</div><div class="title">Java连接MySQL基础教程(JDBC)</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8D%E8%AF%8D%E8%A7%A3%E9%87%8A"><span class="toc-number">1.</span> <span class="toc-text">名词解释</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#SSO-Server"><span class="toc-number">2.</span> <span class="toc-text">SSO-Server</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#pom-xml-%E5%85%B3%E9%94%AE%E4%BE%9D%E8%B5%96"><span class="toc-number">2.1.</span> <span class="toc-text">pom.xml 关键依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84"><span class="toc-number">2.2.</span> <span class="toc-text">项目结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#application-yml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-number">2.3.</span> <span class="toc-text">application.yml配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SsoUserDetailServiceImpl%E7%94%A8%E6%88%B7%E8%AE%A4%E8%AF%81%E6%9C%8D%E5%8A%A1"><span class="toc-number">2.4.</span> <span class="toc-text">SsoUserDetailServiceImpl用户认证服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#WebSecurityConfig%E5%AE%89%E5%85%A8%E8%AE%A4%E8%AF%81%E9%85%8D%E7%BD%AE"><span class="toc-number">2.5.</span> <span class="toc-text">WebSecurityConfig安全认证配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SsoAuthorizationServiceConfig%E8%AE%A4%E8%AF%81%E5%AE%A2%E6%88%B7%E7%AB%AF%E9%85%8D%E7%BD%AE"><span class="toc-number">2.6.</span> <span class="toc-text">SsoAuthorizationServiceConfig认证客户端配置</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#SSO-Client"><span class="toc-number">3.</span> <span class="toc-text">SSO-Client</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#pom-xml%E5%85%B3%E9%94%AE%E4%BE%9D%E8%B5%96"><span class="toc-number">3.1.</span> <span class="toc-text">pom.xml关键依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#application-yml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6-1"><span class="toc-number">3.2.</span> <span class="toc-text">application.yml配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SessionUtil%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E4%BF%A1%E6%81%AF%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-number">3.3.</span> <span class="toc-text">SessionUtil获取用户信息工具类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#WebConfig%E5%AE%89%E5%85%A8%E9%85%8D%E7%BD%AE"><span class="toc-number">3.4.</span> <span class="toc-text">WebConfig安全配置</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%AA%8C%E8%AF%81%E7%BB%93%E6%9E%9C"><span class="toc-number">4.</span> <span class="toc-text">验证结果</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By XY</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my blog! <a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src="https://img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png"><span>蜀ICP备2022030939号</span></a> <a href="https://icp.gov.moe/?keyword=20220702" target="_blank">萌ICP备20220702号</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><div class="js-pjax"><script>(() => {
  const $mermaidWrap = document.querySelectorAll('#article-container .mermaid-wrap')
  if ($mermaidWrap.length) {
    window.runMermaid = () => {
      window.loadMermaid = true
      const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default'

      Array.from($mermaidWrap).forEach((item, index) => {
        const mermaidSrc = item.firstElementChild
        const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n'
        const mermaidID = 'mermaid-' + index
        const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent
        mermaid.mermaidAPI.render(mermaidID, mermaidDefinition, (svgCode) => {
          mermaidSrc.insertAdjacentHTML('afterend', svgCode)
        })
      })
    }

    const loadMermaid = () => {
      window.loadMermaid ? runMermaid() : getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaid)
    }

    window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
  }
})()</script></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="true" data-click="true"></script></div></body></html>